package com.ptszyxx.popose.module.main.map;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.AMapWrapper;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.ptszyxx.popose.BR;
import com.ptszyxx.popose.R;
import com.ptszyxx.popose.common.utils.YActivityUtil;
import com.ptszyxx.popose.common.utils.YVipUtil;
import com.ptszyxx.popose.databinding.FragmentMapBinding;
import com.ptszyxx.popose.module.main.map.vm.MapVM;
import com.ptszyxx.popose.module.main.map.web.MAWebViewWrapper;
import com.ysg.base.BaseFragment;
import com.ysg.db.UserLatLngDb;
import com.ysg.http.data.AppViewModelFactory;
import com.ysg.http.data.entity.home.HomeResult;
import com.ysg.utils.YBitmapUtil;
import com.ysg.utils.YDbUtils;
import com.ysg.utils.YDialogUtil;
import com.ysg.utils.YRandomUtil;
import com.ysg.utils.YSPUtils;
import com.ysg.utils.YStringUtil;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MapFragment extends BaseFragment<FragmentMapBinding, MapVM> {
    private AMap aMap;
    private AMapWrapper mapView;
    private LatLng centerLatLng;
    private Map<String, HomeResult> map = new HashMap<>();

    private float mixZoom = 10;
    private float maxZoom = 14;//500m
    private float currentZoom = 12;
    @Override
    public int initContentView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return R.layout.fragment_map;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public MapVM initViewModel() {
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getActivity().getApplication());
        return ViewModelProviders.of(this, factory).get(MapVM.class);
    }

    @Override
    public void initView() {
        super.initView();
        MAWebViewWrapper webViewWrapper = new MAWebViewWrapper(binding.mapView);
        mapView = new AMapWrapper(getContext(), webViewWrapper);
        mapView.onCreate();

        mapView.getMapAsyn(new AMap.OnMapReadyListener() {
            @Override
            public void onMapReady(AMap map) {
                aMap = map;
                initListener();
                aMap.setMinZoomLevel(mixZoom);
                aMap.setMaxZoomLevel(maxZoom);

                initLocation();
                startLocation();
            }
        });
    }

    @Override
    public void initViewObservable() {
        super.initViewObservable();
        viewModel.uc.onRefreshEvent.observe(this, new Observer<List<HomeResult>>() {
            @Override
            public void onChanged(List<HomeResult> list) {
                generateRandomLatLng(list);
            }
        });
        viewModel.uc.onStartLocationEvent.observe(this, o -> startLocation());
    }

    @Override
    public void onResume() {
        super.onResume();
        mapView.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        mapView.onPause();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
        destroyLocation();
    }

    /**
     * 初始化定位
     */
    private AMapLocationClient locationClient = null;
    private AMapLocationClientOption locationOption = null;

    private void initLocation() {
        try {
            AMapLocationClient.updatePrivacyAgree(getContext(), true);
            AMapLocationClient.updatePrivacyShow(getContext(), true, true);
            locationClient = new AMapLocationClient(getContext());
            locationOption = getDefaultOption();
            //设置定位参数
            locationClient.setLocationOption(locationOption);
            // 设置定位监听
            locationClient.setLocationListener(locationListener);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 默认的定位参数
     */
    private AMapLocationClientOption getDefaultOption() {
        AMapLocationClientOption mOption = new AMapLocationClientOption();
        mOption.setGpsFirst(true);//可选，设置是否gps优先，只在高精度模式下有效。默认关闭
        mOption.setInterval(1000);//可选，设置定位间隔。默认为2秒
        mOption.setOnceLocation(false);//可选，设置是否单次定位。默认是false
        mOption.setLocationCacheEnable(false); //可选，设置是否使用缓存定位，默认为true
        mOption.setGeoLanguage(AMapLocationClientOption.GeoLanguage.DEFAULT);//可选，设置逆地理信息的语言，默认值为默认语言（根据所在地区选择语言）
        return mOption;
    }

    /**
     * 定位监听
     */
    private AMapLocation perLocation;
    AMapLocationListener locationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation location) {
            if (null != location) {
                stopLocation();

                StringBuffer sb = new StringBuffer();
                //errCode等于0代表定位成功，其他的为定位失败，具体的可以参照官网定位错误码说明
                if (location.getErrorCode() == 0) {
                    sb.append("经    度    : " + location.getLongitude() + "\n");
                    sb.append("纬    度    : " + location.getLatitude() + "\n");
                    sb.append("省            : " + location.getProvince() + "\n");
                    sb.append("市            : " + location.getCity() + "\n");
                    sb.append("区            : " + location.getDistrict() + "\n");
                    sb.append("地    址    : " + location.getAddress() + "\n");
                    //防止地址是空的
                    if (YStringUtil.isNotEmpty(location.getAddress())){
                        perLocation = location;
                        centerLatLng = new LatLng(perLocation.getLatitude(), perLocation.getLongitude());
                    }
                    if (perLocation != null){
                        jumpToCenter(centerLatLng);
                        viewModel.requestMapList(perLocation.getAddress());
                    }
                } else {
                    //定位失败
                    sb.append("定位失败" + "\n");
                    sb.append("错误码:" + location.getErrorCode() + "\n");
                    sb.append("错误信息:" + location.getErrorInfo() + "\n");
                    sb.append("错误描述:" + location.getLocationDetail() + "\n");
                }
                //解析定位结果，
                String result = sb.toString();
                Log.e("定位结果：", result);
            }
        }
    };

    /**
     * 生成随机经纬度
     */
    private void generateRandomLatLng(List<HomeResult> list) {
        String latPrefix = String.valueOf(centerLatLng.latitude).substring(0, 4);
        String lngPrefix = String.valueOf(centerLatLng.longitude).substring(0, 5);

        String loginUserId = YSPUtils.getInstance().getUserId();
        for(HomeResult item: list){
            UserLatLngDb data = YDbUtils.getInstance().findOneUserLatLng(loginUserId, item.getUserid() + "");
            String newLat = "", newLng = "";
            if (data != null && data.getLat() != null && data.getLng() != null){
                newLat = data.getLat();
                newLng = data.getLng();
            }else{
                newLat = latPrefix + YStringUtil.zeroFill(YRandomUtil.getThousand()+"");
                newLng = lngPrefix + YStringUtil.zeroFill(YRandomUtil.getThousand()+"");
                UserLatLngDb save = new UserLatLngDb();
                save.setLoginUserId(loginUserId);
                save.setUserId(item.getUserid() + "");
                save.setUserName(item.getUsernick());
                save.setLat(newLat);
                save.setLng(newLng);
                YDbUtils.getInstance().saveUserLatLng(save);
            }
            try {
                Log.e("经纬度" , "newLat:" + newLat + " newLng:"+newLng + " userId:"+item.getUserid());
                LatLng latLng = new LatLng(Double.valueOf(newLat), Double.valueOf(newLng));
                addMarkerFromUrl(item, latLng, false);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    /**
     * 开始定位
     */
    private void startLocation() {
        try {
            locationClient.setLocationOption(locationOption);
            locationClient.startLocation();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 停止定位
     */
    private void stopLocation() {
        try {
            locationClient.stopLocation();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 销毁定位
     */
    private void destroyLocation() {
        if (null != locationClient) {
            locationClient.onDestroy();
            locationClient = null;
            locationOption = null;
        }
    }

    /**
     * 跳转到中心点
     */
    private void jumpToCenter(LatLng latLng) {
        CameraUpdate update = CameraUpdateFactory.newCameraPosition(new CameraPosition(latLng, currentZoom, 30, 30));//当前缩放等级15
        aMap.moveCamera(update);
        aMap.clear();

        //添加标记物
        HomeResult data = new HomeResult();
        data.setUserid(YSPUtils.getInstance().getUserId());
        data.setUsericon(YSPUtils.getInstance().getUserPic());
        addMarkerFromUrl(data, latLng, true);
    }


    public void addMarkerFromUrl(HomeResult data, LatLng latLng, boolean isSelf){
        YBitmapUtil.getMapBitmap(data.getUsericon(), isSelf, new YBitmapUtil.OnMapBitmapListener() {
            @Override
            public void onSuccess(Bitmap bitmap) {
                BitmapDescriptor descriptor = BitmapDescriptorFactory.fromBitmap(bitmap);
                MarkerOptions markerOption = new MarkerOptions().icon(descriptor).position(latLng);
                Marker marker = aMap.addMarker(markerOption);
                marker.setTitle(data.getUserid() + "");
                map.put(data.getUserid() + "", data);
            }

            @Override
            public void onError(Exception e) {
            }
        });
    }


    /**
     * 点击标记物监听
     */
    private void initListener(){
        aMap.setOnMarkerClickListener(new AMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                //判断是否开通会员
                HomeResult data = map.get(marker.getTitle());
                if (YVipUtil.isVip(getContext(), true)){
                    YActivityUtil.getInstance().jumpUserDetail(viewModel, data.getUserid());
                }
                return true;
            }
        });
    }


}
